from Common import *

class URLBackup:
    ''' 用于把请求url转换成字符串记录在文件中
        或者把文件中的字符串转换成url
    '''
    def __init__(self):
        self.fileName = 'data/commit.backup'

        # 只有在這個集合中的接口才會被記錄
        self.writfulInterface = { \
            'account_add', 'account_delete', 'account_edit', \
            'category_addIncome', 'category_addPaymentCat1', 'category_addPaymentCat2', 'category_addTransfer', \
            'category_deleteIncome', 'category_deletePaymentCat1', 'category_deletePaymentCat2', 'category_deleteTransfer', \
            'category_editIncome', 'category_editPaymentCat1', 'category_editPaymentCat2', 'category_editTransfer', \
            'currency_add', 'currency_edit', 'currency_delete', \
            'record_addIncome','record_addPayment','record_addTransfer', 'record_addPaymentRecordsByText', \
            'record_deleteIncome', 'record_deletePayment', 'record_deleteTransfer', \
            'record_editIncode', 'record_editPayment', 'record_editTransfer', \
            'budget_setCat1'
        }

    def backup(self, service_name, method_name, args):
        ''' 把请求三元组(service_name, method_name, args)记录在文件中
            无返回值
        '''
        key = service_name + '_' + method_name
        if key not in self.writfulInterface:
            return
        line = commitReqToStr(service_name, method_name, args)
        f = open(self.fileName, 'a')
        f.write(line)
        f.close()

    def load(self, file_path):
        ''' 把文件中的每一行转换成请求三元组(service_name, method_name, args)
            成功返回一个三元组的列表，否则返回-1
        '''
        ret = []
        try:
            f = open(file_path)
            while True:
                line = f.readline()
                if line == '':
                    break
                if line.strip() == '':
                    continue
                service_name, method_name, args = strToCommitReq(line)
                ret.append((service_name, method_name, args))
            f.close()
        except:
            return -1
        if len(ret) == 0:
            return -1
        return ret
